---管理代理的所有目标
---@class GoalManagerBase
---@field goalsDic table<string,GoalBase>
---@field agent AgentBase
---@field currentGoal GoalBase  当前目标
---@field activeGoals GoalBase[]  激活的同时存在的目标
---@field base GoalManagerBase
GoalManagerBase = class()

function GoalManagerBase:ctor(agent)
    self.base = GoalManagerBase;
    self.agent = agent;
    self.currentGoal = nil;
    self.goalsDic = {}
    self.activeGoals = {}
    self:InitGoals();
end

---初始化所有目标，子类重写
function GoalManagerBase:InitGoals() end

---添加goal
---@param label string
function GoalManagerBase:AddGoal(label)
    if self.goalsDic[label] ~= nil then
        Debug.LogError("重复添加目标："..label)
    end
    local goal = self.agent.dataMap:GetGoal(label);
    if goal == nil then
        Debug.LogError("添加目标"..label.."出错，未在Map中找到该目标")
        return
    end
    if self.goalsDic[label] ~= nil then
        Debug.LogError("目标已经存在，重复添加goal到Manager:"..label);
    end
    self.goalsDic[label] = goal;
    goal:SetGoalActiveteCallFunc(function (activeGoal)
        local index = table.indexOf(self.activeGoals,activeGoal)
        if index == -1 then
            table.insert(self.activeGoals,activeGoal);
        end
    end)
    goal:SetGoalInactivateCallFunc(function (activeGoal)
        local index = table.indexOf(self.activeGoals,activeGoal)
        if index ~= -1 then
            self.activeGoals = table.removeArrayKey(self.activeGoals,index)
        end
    end)
end

---移除目标
function GoalManagerBase:RemoveGoal(lable)
    self.goalsDic[lable] = nil;
end

---获取目标
function GoalManagerBase:GetGoal(lable)
    if self.goalsDic[lable] ~= nil then
        return self.goalsDic[lable];
    end
    Debug.LogError("未找到该目标："..lable);
    return nil;
end

---查找优先级最高的那个目标
---@return GoalBase
function GoalManagerBase:FindGoal()
    if #self.activeGoals == 0 then
        return nil;
    end
    if #self.activeGoals == 1 then
        return self.activeGoals[1];
    end
    ---按照优先级排序
    table.sort(self.activeGoals,function (a,b)
        return a:GetPriority() > b:GetPriority();
    end)
    return self.activeGoals[1];
end

---数据更新时执行
function GoalManagerBase:UpdateData()
    self:UpdateGoals();
    self:UpdateCurrentGoal();
end

---更新所有Goal的信息
function GoalManagerBase:UpdateGoals()
    for k, v in pairs(self.goalsDic) do
        v:UpdateData();
    end
end

---更新当前Goal对象
function GoalManagerBase:UpdateCurrentGoal()
    local goalLable = nil;
    if self.currentGoal ~= nil then
        goalLable = self.currentGoal.label;
    end
    self.currentGoal = self:FindGoal();
    if self.currentGoal == nil then
        Debug.Log("当前Goal为空！")
    else
        Debug.Log("当前Goal更新为："..self.currentGoal.label);
        ---如果更换了目标，则尝试打断当前执行的动作
        if goalLable ~= nil and goalLable ~= self.currentGoal.label then
            self.agent.performer:TryInterruptAction();
        end
    end
end

